package com.example.demo.internettongxin.qunliao;

import java.io.*;
import java.net.Socket;
import java.security.PublicKey;

/**
 * @Description T3clientReaderthread
 * @Author songchuanlong
 * @Date 2025-05-30
 */
public class T3clientReaderthread extends Thread{
    private Socket socket;
    public T3clientReaderthread (Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg);
                    sendMessageAll(msg);
                } catch (IOException e) {
                    System.out.println("有人离线了"+socket.getRemoteSocketAddress());
                    T3server.onLine.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
    }

    /**
     * 当服务器接收到某个客户端的消息后，比如 "Hello"，希望把这个消息广播给所有已连接的客户端。
     * 所以必须遍历 T3server.onLine，拿到每一个客户端的 Socket，然后通过它们的输出流向每个客户端发送消息。
     * @param msg
     * @throws IOException
     */
    private void sendMessageAll(String msg) throws IOException {
        for (Socket socket1 : T3server.onLine) {
            OutputStream os = socket1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}
